﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WXY.Course.Common.Log;

namespace WXY.Course.Web.Areas.Admin.Filter
{
    public class JsonExceptionFilter : FilterAttribute, IExceptionFilter
    {
        private Logger logger;
        private JsonRequestBehavior behavior;

        public JsonExceptionFilter(Type type, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet)
        {
            this.logger = new Logger(type);
            this.behavior = behavior;
        }

        public void OnException(ExceptionContext filterContext)
        {
            logger.ErrorFormat(filterContext.Exception);

            var ajaxResult = new
            {
                IsSuccess = false,
                Message = filterContext.Exception.Message,
            };

            filterContext.Result = new JsonResult { Data = ajaxResult, JsonRequestBehavior = behavior };

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}